package gl.android.xmppandroidclient.server;

import gl.android.util.NotificationUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jivesoftware.smack.XMPPException;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

public class XmppService extends Service {
	public class ChatClientBinder extends ChatClient.Stub {

		@Override
		public void sendMessage(final String to, final String messageBody)
				throws RemoteException {
			singleThreadExecutor.submit(new Runnable() {

				@Override
				public void run() {
					System.out.println("sendMessage to " + to + ":"
							+ messageBody);
					XmppManger.getInstance().sendmessage(to, messageBody);

				}
			});

		}

		@Override
		public void login(final String account, final String password)
				throws RemoteException {
			singleThreadExecutor.submit(new Runnable() {
				@Override
				public void run() {
					try {
						XmppConfig mXmppConfig = new XmppConfig();
						mXmppConfig.configAccount(account, password);
						if (XmppManger.getInstance().init(getContext(),
								mXmppConfig)) {
							XmppManger.getInstance().login();
						}
						
					} catch (XMPPException e) {
						e.printStackTrace();
					}

				}
			});

		}

	}

	/**
	 * 通信接口存根
	 */
	ChatClientBinder mChatClientBinder = new ChatClientBinder();
	
	/**
	 * 任务 异步顺序执行线程池
	 */
	ExecutorService singleThreadExecutor;

	AndroidXmppStateHandler mAndroidXmppStateHandler;
	@Override
	public void onCreate() {
		System.out.println("onCreate service ......");
		singleThreadExecutor = Executors.newSingleThreadExecutor();
		mAndroidXmppStateHandler= new AndroidXmppStateHandler(getApplicationContext());
		XmppManger.getInstance().setXmppStateHandler(mAndroidXmppStateHandler);
	};

	private Context getContext() {
		return getApplicationContext();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// 如果是被系统杀死
		// 即按home键清除出任务，下面的返回值能保证service重新启动（前提是没有调用service的destory方法,并且service是非bind形式）
		System.out.println("onStartCommand ......");
		return START_STICKY;
	}

	/**
	 * When binding to the service,we return an interface to our messenger for
	 * sending messages to the service
	 */
	@Override
	public IBinder onBind(Intent intent) {
		showToast("bind service");
		System.out.println("onBind service...");
		return mChatClientBinder;
	}

	private void showToast(String message) {
	}

	@Override
	public void onDestroy() {
		System.out.println("onDestroy...");
		singleThreadExecutor.submit(new Runnable() {
			public void run() {
				XmppManger.getInstance().destory();
			}
		});
		super.onDestroy();
		singleThreadExecutor.shutdownNow();
		NotificationUtil
				.destoryPersistenceNotification(getApplicationContext());
	}
}
